<template>
  <a-tree-select
    v-bind="$attrs"
    :disabled="disabled"
    v-model="currentValue"
    :treeData="treeData"
    :replaceFields="{ children: 'children', title: 'label', key: 'id',value:'id' }"
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    placeholder="请选择"
    @select="onSelect"
  >
    <a-icon
      v-if="loading"
      style="color: #096dd9"
      slot="suffixIcon"
      type="loading"
    />
    <a-spin
      v-if="loading"
      slot="notFoundContent"
      size="small"
    />
  </a-tree-select>

</template>

<script>
import { getCustOrgTree } from '@/api/subassembly/TreeSelectOrganization'

/*
* 示例
* 表单：
注：只要选中条目的id，可以不监听onSelectChange事件
<SelectCompanyAndProject
    disabled
    :auto-select="true"
    v-model="formData.depId"
    @onSelectChange="formData.depName = $event.name">
</SelectCompanyAndProject>

搜索框：
{
    name: '单位',
    valueKey: 'depId',
    type: SelectCompanyAndProject
},
*
*说明：
* 自动判断当前岗位，
* 如果是PD，则手动生成一条数据
* 如果是CO，则显示所有数据
* 如果是BC，则循环所有数据，匹配到对应的数据，然后单独取出来放到treeData里面
*
* onSelectChange事件：
* 数据改变时会发射onSelectChange事件，$event为{ id , name} , 根据需要自己取 ，name值是上级加上本级的名字，如: 四川分公司 - 综合管理部 ，
* id是选中条目的id
*
* */
export default {
  // v-model绑定的数据
  props: {
    value: {
      type: [Array, String, Object]
    },
    orgName: {
      type: [Array, String, Object]
    },
    disabled: {
      type: Boolean,
      default: false
    },
    //是否根据用户权限筛选数据
    isAuth: {
      type: Boolean,
      default: true
    },
    //是否自动选中我
    isAutoSelectMe: {
      type: Boolean,
      default: false
    },
    // 请求的额外参数
    extraParams: {
      type: Object,
      default: () => ({})
    },
    userType: null,
    isEdit: false,
    orgParentId: null
  },
  data() {
    return {
      treeData: [],
      loading: false,
      lUserType: null,
      recursionId: null
    }
  },
  mounted() {
    this.lUserType = this.$userType()
    if (!this.isEdit) {
      this.getCompanyList()
    }
  },
  watch: {
    isEdit(val) {
      if (val) {
        this.lUserType = this.userType
        this.getCompanyList()
      }
    }
  },
  methods: {
    onSelect(e, node) {
      console.log(e, node)
      let parent = node.$parent.$vnode.data.props
      console.log(parent)
      let child = node.$vnode.data.props
      let name = ''
      let code // 组织code
      let codeName // 组织code名称
      let tag = child.data.tag // 组织标签
      // 根据标签获取当前选项的组织code
      if (tag.includes('CO')) {
        code = 'CO'
        codeName = '公司'
      } else if (tag.includes('BC')) {
        code = 'BC'
        codeName = '分公司'
      } else if (tag.includes('PD')) {
        code = 'PD'
        codeName = '项目'
        if (parent.id) {
          name = parent.title + ' - '
        }
      }
      name = name + child.title
      this.$emit('onSelectChange', { id: e, name, code, codeName, parentId: parent.id })
      code && this.$emit('update:orgCode', code)
      codeName && this.$emit('update:orgCodeName', codeName)
    },
    async getCompanyList() {
      let params = Object.assign(
        {},
        {
          baseOrgType: 0, // 是否基础组织 0否 1是
          containVirtual: 0, //是否包含虚拟组织 0包含 1 不包含
          systemOrgType: 1 //公司组织默认1
        },
        this.extraParams
      )
      this.loading = true
      let res = await getCustOrgTree(params)
      this.loading = false

      if (this.isAuth) {
        if (this.lUserType === 'PD') {
          if (this.value) {
            this.treeData = [
              {
                id: this.value,
                label: this.orgName,
                children: [],
                data: { tag: ['PD'] }
              }
            ]
          } else {
            this.treeData = [
              {
                id: this.$currentPost().id,
                label: this.$currentPost().orgName + ' - ' + this.$currentPost().name,
                children: [],
                data: { tag: ['PD'] }
              }
            ]
          }
          if (this.isAutoSelectMe) {
            this.currentValue = this.treeData[0].id
            this.$emit('onSelectChange', {
              id: this.treeData[0].id,
              name: this.treeData[0].label
            })
          }
          return
        }
        //如果用户岗位是分公司
        if (this.lUserType === 'BC') {
          if (this.value) {
            if (this.orgParentId) {
              this.recursionId = this.orgParentId
            } else {
              this.recursionId = this.value
            }
            this.recursion2(res.data, null)
          } else {
            this.recursion(res.data, null)
          }
        } else {
          this.treeData = res.data
          if (this.isAutoSelectMe) {
            this.currentValue = this.treeData[0].id
            this.$emit('onSelectChange', {
              id: this.treeData[0].id,
              name: this.treeData[0].label
            })
          }
        }
      } else {
        this.treeData = res.data
        if (this.isAutoSelectMe) {
          this.currentValue = this.treeData[0].id
          this.$emit('onSelectChange', {
            id: this.treeData[0].id,
            name: this.treeData[0].label
          })
        }
      }
    },
    recursion2(items, parent) {
      for (let i = 0; i < items.length; i++) {
        let item = items[i]
        if (item.id === this.recursionId) {
          this.treeData = [item]
          if (this.isAutoSelectMe) {
            this.currentValue = this.treeData[0].id
            this.$emit('onSelectChange', {
              id: this.treeData[0].id,
              // name: parent.label + '-' + item.label
              name: item.label
            })
          }
        } else {
          if (item.children) {
            this.recursion2(item.children, item)
          }
        }
      }
    },
    recursion(items, parent) {
      for (let i = 0; i < items.length; i++) {
        let item = items[i]
        if (item.id === this.$currentPost().id) {
          this.treeData = [item]
          if (this.isAutoSelectMe) {
            this.currentValue = this.treeData[0].id
            this.$emit('onSelectChange', {
              id: this.treeData[0].id,
              // name: parent.label + '-' + item.label
              name: item.label
            })
          }
        } else {
          if (item.children) {
            this.recursion(item.children, item)
          }
        }
      }
    }
  },
  computed: {
    // 转换绑定的选中数据，与v-model同步
    currentValue: {
      get: function () {
        return this.value
      },
      set: function (value) {
        // console.log(value)
        this.$emit('input', value)
        this.$emit('change', value)
      }
    }
  }
}
</script>
